package delay;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author honway.liu
 * @date 2018/5/10 下午10:32
 * @email gm100861@gmail.com
 * @blog http://linuxsogood.org
 */
@Data
@NoArgsConstructor
@Log4j
public class Message implements Delayed {

    private int id;

    private Long delayTime;

    private String data;


    public Message(int id, Long delayTime, String data) {
        this.id = id;
        this.delayTime = delayTime + System.currentTimeMillis();
        this.data = data;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.delayTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        if (o instanceof Message) {
            Message message = (Message) o;
            return Long.compare(this.getDelay(TimeUnit.MILLISECONDS), message.getDelay(TimeUnit.MILLISECONDS));
        }
        return 0;
    }
}
